<template>
  <div m-0>
    <VueEditor :editor="editor" />
  </div>
</template>

<script setup lang="ts">
// core
import { VueEditor, useEditor } from "@milkdown/vue";
import { Editor, rootCtx, defaultValueCtx, editorViewCtx, parserCtx } from "@milkdown/core";
import { nord } from "@milkdown/theme-nord";
import { commonmark } from "@milkdown/preset-commonmark";
import { Slice } from "prosemirror-model";

// plugin
import { emoji } from "@milkdown/plugin-emoji";
import { menu } from "@milkdown/plugin-menu";
import { slash } from "@milkdown/plugin-slash";
import { history } from "@milkdown/plugin-history";
import { prism } from "@milkdown/plugin-prism";
import { tooltip } from "@milkdown/plugin-tooltip";
import { indent } from "@milkdown/plugin-indent";
import { trailing } from "@milkdown/plugin-trailing";
import { upload } from "@milkdown/plugin-upload";
import { cursor } from "@milkdown/plugin-cursor";
import { clipboard } from "@milkdown/plugin-clipboard";
import { listener, listenerCtx } from "@milkdown/plugin-listener";

import "prismjs/themes/prism.css";
import { useMarkdownStore } from "~/store/markdown";
import { storeToRefs } from "pinia";

// const emit = defineEmits<{
//   (e: "update:modelValue", value: string): void;
// }>();

const markdownStore = useMarkdownStore()
const { content, isSaved, openning } = storeToRefs(markdownStore)
watch(content, () => {
  if (isSaved.value) {
    if (openning.value) {
      openning.value = false
    } else {
      isSaved.value = false;
    }
  } else if (!isSaved.value) {
    //fix: 修改文件后再打开新文件时显示未保存
    if (openning.value) {
      openning.value = false
      isSaved.value = true
    }
  }
})

watch(openning, (curOpenning) => {
  if (curOpenning) {
    getInstance()?.action(ctx => {
      const view = ctx.get(editorViewCtx);
      const parser = ctx.get(parserCtx);
      const doc = parser(content.value);
      if (!doc) return;
      const state = view.state;
      view.dispatch(
        state.tr.replace(
          0,
          state.doc.content.size,
          new Slice(doc.content, 0, 0)
        )
      );
    })
    //openning.value = false
  }
})

const { editor, getInstance } = useEditor((root) =>
  Editor.make()
    .config((ctx) => {
      ctx.set(rootCtx, root);
      ctx.set(defaultValueCtx, content.value);
      ctx.get(listenerCtx).markdownUpdated((ctx, markdown) => {
        content.value = markdown
      });
    })
    .use(nord)
    .use(emoji)
    .use(slash)
    .use(commonmark)
    .use(menu)
    .use(history)
    .use(prism)
    .use(tooltip)
    .use(indent)
    .use(trailing)
    .use(upload)
    .use(cursor)
    .use(clipboard)
    .use(listener)
);
</script>
